import config from './config';
import { Exceptions } from '../kalend';

var xmlreader = require("xmlreader");
var crypto = require('crypto');
var Decimal = require('decimal.js');


class Common {
    // 随机创建code,默认15位
    buildCode(len?: number) {
        let recode = '';
        if (len) {
            let str = new Date().getTime().toString() + Math.random().toString(10).replace('.', '');
            if (len <= str.length) {
                recode = str.substring(str.length - len);
            } else {
                for (let index = 0; index < len - str.length; index++) {
                    recode += '0';
                }
                recode = str + recode;
            }
        } else {
            let timstr = new Date().getTime().toString();
            recode = timstr.substr(timstr.length - 6, 6) + Math.random().toString(10).replace('.', '').substr(5, 8);
        }
        return recode;
    }

    //把金额转为分
    getmoney(money: any) {
        return new Decimal(money).mul(new Decimal(100)).toNumber().toFixed(2);
    }
    /** 相加 */
    add(num1: number, num2: number) {
        return new Decimal(num1).add(new Decimal(num2)).toNumber().toFixed(2);
    }
    /** 相减 */
    sub(num1: number, num2: number) {
        return new Decimal(num1).sub(new Decimal(num2)).toNumber().toFixed(2);
    }
    /** 乘法 */
    mul(num1: number, num2: number) {
        return new Decimal(num1).mul(new Decimal(num2)).toNumber().toFixed(2);
    }
    /** 除法 */
    div(num1: number, num2: number) {
        return new Decimal(num1).div(new Decimal(num2)).toNumber().toFixed(2);
    }

    // 随机字符串产生函数  
    createNonceStr() {
        return Math.random().toString(36).substr(2, 15);
    };
    // 随机字符串产生函数  
    createtokenStr() {
        return Math.random().toString(36);
    };

    // 时间戳产生函数  
    createTimeStamp() {
        return parseInt(new Date().getTime() / 1000 + '');
    }
    xml2json(xml: any) {
        xmlreader.read(xml, (errors: any, response: any) => {
            if (null !== errors) {
                console.log(errors)
                return;
            }
            return response.xml;
        });
    }
    //签名加密算法
    makesign(ret: any, mchkey: any) {
        var string = this.raw(ret);
        var key = mchkey;
        string = string + '&key=' + key;
        console.log('签名=', string);
        return crypto.createHash('MD5').update(string, 'utf8').digest('hex').toUpperCase();
    }
    raw(args: any) {
        var keys = Object.keys(args);
        keys = keys.sort()
        var newArgs: any = {};
        keys.forEach(function (key) {
            newArgs[key] = args[key];
        });
        var string = '';
        for (var k in newArgs) {
            string += '&' + k + '=' + newArgs[k];
        }
        string = string.substr(1);
        return string;
    }

    json2Xml(json: any) {
        let _xml = '';
        Object.keys(json).map((key) => {
            _xml += `<${key}>${json[key]}</${key}>`
        })
        return `<xml>${_xml}</xml>`;
    }


    signstring(str: string, signType: string) {
        return crypto.createHash(signType).update(str, 'utf8').digest('hex').toUpperCase();
    }

    decryptData(encryptedData: any) {
        let that = this;
        let jwtConfig = config.get('tokensoft');
        var noncestr = new Buffer(jwtConfig.noncestr, 'base64')
        encryptedData = new Buffer(encryptedData, 'base64')
        let iv = new Buffer(jwtConfig.iv, 'base64')

        let decoded: any;
        try {
            // 解密
            var decipher = crypto.createDecipheriv('MD5', noncestr, iv)
            // 设置自动 padding 为 true，删除填充补位
            decipher.setAutoPadding(true)
            decoded = decipher.update(encryptedData, 'binary', 'utf8')
            decoded += decipher.final('utf8')
            console.log(decoded);
            decoded = JSON.parse(decoded)

        } catch (err) {
            console.log(err);
            throw Exceptions.unknown(err);
        }
        return decoded;
    }
}

export const common = new Common();